package com.atguigu.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.search.config.GulimallElasticSearchConfig;
import com.atguigu.search.constants.EsConstant;
import com.atguigu.search.feign.ProductFeignService;
import com.atguigu.search.service.MallSearchService;
import com.atguigu.search.vo.AttrResponseVo;
import com.atguigu.search.vo.SearchParam;
import com.atguigu.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import org.elasticsearch.search.aggregations.AggregationBuilders;

import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;



@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    //去es中进行检索
    @Override
    public SearchResult search(SearchParam param) {

        //1. 动态构建出查询需要的DSL语句
        SearchResult result = null;

        //1. 准备检索请求
        SearchRequest request = buildSearchRequest(param);

        try {
            //2. 执行检索请求
            SearchResponse response = client.search(request, GulimallElasticSearchConfig.COMMON_OPTIONS);
            // 3、分析相应数据并封装成需要的指定格式
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return result;
    }

    /**
     * 准备检索请求
     * 模糊匹配：过滤（按照属性、分类、品牌、价格区间、库存）、排序、分页、高亮，聚合分析
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        //构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         *  模糊匹配：过滤（按照属性、分类、品牌、价格区间、库存）
         */
        //1.构建布尔查询
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            //1.1 match模糊匹配
            boolBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }

        //1.2 filter过滤(按照分类、品牌、属性、库存、价格区间)
        //1.2.1 按照三级分类id查询
        if (param.getCatalog3Id() != null) {
            boolBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        //1.2.2 按照品牌id查询
        if (!CollectionUtils.isEmpty(param.getBrandId()) && param.getBrandId().size() > 0) {
            boolBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }

        //1.2.3 按照属性进行查询
        if (!CollectionUtils.isEmpty(param.getAttrs()) && param.getAttrs().size() > 0) {
            // attrs=1_其他:安卓&attrs=2_5寸:1.5寸
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolBuilder = QueryBuilders.boolQuery();

                String[] s = attrStr.split("_");
                String attrId = s[0];//检索的属性id
                String[] attrValues = s[1].split(":");//检索的属性值

                nestedBoolBuilder.must(QueryBuilders.termsQuery("attrs.attrId", attrId));
                nestedBoolBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));

                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", nestedBoolBuilder, ScoreMode.None);
                boolBuilder.filter(nestedQueryBuilder);

            }

        }

        //1.2.4 按照是否拥有库存进行查询
        if (param.getHasStock() != null) {
            boolBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

        //1.2.5 按照价格区间进行查询
        if (StringUtils.isNotEmpty(param.getSkuPrice())) {
            // 1_500/_500/500_
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");

            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                //区间
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {

                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }

                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }

            }

            boolBuilder.filter(rangeQuery);
        }

        sourceBuilder.query(boolBuilder);


        /**
         *     排序、分页、高亮，聚合分析
         */
        //2.排序
        if (StringUtils.isNotEmpty(param.getSort())) {

            String sort = param.getSort();
            // sort=saleCount_desc/asc
            String[] s = sort.split("_");//saleCount_desc
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }

        //3. 分页
        sourceBuilder.from((param.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //4. 高亮
        if ( StringUtils.isNotEmpty(param.getKeyword()) ) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }


        /**
         * 聚合分析
         */
        //5.1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        //TODO 品牌聚合
        sourceBuilder.aggregation(brand_agg);


        TermsAggregationBuilder catelog_agg = AggregationBuilders.terms("catelog_agg").field("catalogId").size(20);
        catelog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        //TODO 分类聚合
        sourceBuilder.aggregation(catelog_agg);

        NestedAggregationBuilder attrs_agg = AggregationBuilders.nested("attrs_agg", "attrs");//嵌入聚合
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //聚合id
        attrs_agg.subAggregation(attr_id_agg);
        //聚合属性名
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
       //聚合属性值
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        //TODO 属性聚合
        sourceBuilder.aggregation(attrs_agg);

        System.out.println("构建的DSL:->" + sourceBuilder.toString());
        SearchRequest request = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);

        return request;

    }


    /**
     * 构建结果数据
     *
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();

        SearchHits hits = response.getHits();

        //1 .返回所有查询到的商品
        ArrayList<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits()!=null &&  hits.getHits().length>0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //TODO 关键字高亮是通过keyword字段来判断的，如果带有keyword字段就有高亮
                if (StringUtils.isNotEmpty(param.getKeyword())) {

                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }

                esModels.add(skuEsModel);
            }
        }
        result.setProducts(esModels);


        //2. 当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrsVo> attrsVos= new ArrayList<>();
        //2.1 获取属性聚合
        ParsedNested attrs_agg = response.getAggregations().get("attrs_agg");
        //2.2 获取属性id聚合
        ParsedLongTerms attr_id_agg = attrs_agg.getAggregations().get("attr_id_agg");

        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrsVo attrsVo = new SearchResult.AttrsVo();
            //1.得到属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            //2.得到属性名
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            //3.得到属性值
            List<String> attrValue = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                return ((Terms.Bucket)item).getKeyAsString();
            }).collect(Collectors.toList());
            attrsVo.setAttrId(attrId);
            attrsVo.setAttrName(attrName);
            attrsVo.setAttrValue(attrValue);
            attrsVos.add(attrsVo);
        }

        result.setAttrs(attrsVos);


        //3. 当前所有商品涉及到的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {

            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //3.1 得到品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            //3.2 得到品牌名称
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            //3.3 得到品牌图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }

        result.setBrands(brandVos);
        //4. 当前所有商品涉及到的所有分类信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catelog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            // 得到分类id
            catalogVo.setCatalogId(bucket.getKeyAsNumber().longValue());
            // 得到分类name
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        //5. 分页信息-页码
        result.setPageNum(param.getPageNum());
        //5. 分页信息-总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //5. 分页信息-总页码
        int totalPage =(int)total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int)total / EsConstant.PRODUCT_PAGESIZE :  ((int)total / EsConstant.PRODUCT_PAGESIZE+1);
        result.setTotalPage(totalPage);

        //把每一页的页码遍历到List中
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            pageNavs.add(i);
        }

        result.setPageNavs(pageNavs);

        //6. TODO构建面包屑功能
        if ( param.getAttrs()!=null && param.getAttrs().size()>0 ) {
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //attrs=1_5寸:2_6寸  解析attrs参数
                String[] s = attr.split("_");

                //远程调用商品服务根据attrs解析到的attrId查询面包屑名称
                R attrInfo = productFeignService.attrInfo(Long.parseLong(s[0]));
                if (attrInfo.getCode() == 0) {
                    AttrResponseVo data = attrInfo.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }
                //设置面包屑的值
                navVo.setNavValue(s[1]);

                //取消了这个面包屑以后， 我们要跳转到哪个地方，将请求地址的url里面的当前属性值为空
                //拿到所有的查询条件，去掉当前
                //attrs=15_海思（Hisilicon）
                String queryString = param.get_queryString();
                String encode = null;
                try {
                  encode = URLEncoder.encode(attr, "UTF-8");
                  //浏览器处理空格和java编码不一样，浏览器的url中的空格，在java中变成了“+”
                  encode = encode.replace("+", "%20");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                String replace = queryString.replace("&attrs=" + encode, "");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);

                //2. 取消了面包屑后，跳转到哪个地方
                return navVo;
            }).collect(Collectors.toList());

            result.setNavs(collect);
        }



        return result;
    }
}
